package com.zyz.bookborrowing.servlet;

/*
 * 用户的Servlet
 */

import com.zyz.bookborrowing.bean.User;
import com.zyz.bookborrowing.service.IUserService;
import com.zyz.bookborrowing.service.UserServiceImpl;
import com.zyz.bookborrowing.utils.Constant;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.List;

@WebServlet(name = "UserServlet", urlPatterns = "/userServlet")
public class UserServlet extends HttpServlet {

    private IUserService userService = new UserServiceImpl();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req, resp);
    }

    /**
     * 统一处理浏览器提交的 userServlet 的请求
     * @param req 封装请求相关信息的对象
     * @param resp 封装响应相关信息的对象
     * @throws ServletException
     * @throws IOException
     */
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//        设置POST请求中数据的解码方式
//        req.setCharacterEncoding("UTF-8");
//        拦截器 CharacterEncodingFilter 已完成了配置

        String type = req.getParameter(Constant.REQUEST_PARAMETER_TYPE);
        if (type != null && !"".equals(type)) {
            if (Constant.SERVLET_TYPE_SAVE.equals(type)) {
//                添加用户信息
                saveUpUser(req, resp);
            } else if (Constant.SERVLET_TYPE_UPDATE.equals(type)) {
//                更新用户信息
//                用户update和save公用一个方法，方法里if语句判断是何操作
            } else if (Constant.SERVLET_TYPE_DELETE.equals(type)) {
//                删除用户信息
                deleteUserById(req, resp);
            } else if (Constant.SERVLET_TYPE_QUERY.equals(type)) {
//                查询用户
                queryUser(req, resp);
            } else if (Constant.SERVLET_TYPE_QUERYBYID.equals(type)) {
//                查询单条记录
                String id = req.getParameter("id");
                User user = userService.queryById(Integer.parseInt(id));
//                跳转到更新页面，并保存数据到Request作用域
                req.setAttribute("user", user);
                req.getRequestDispatcher("/user/userUpdate.jsp").forward(req, resp);
            } else if (Constant.SERVLET_TYPE_CHECK.equals(type)) {
//                验证账号是否存在
                String userName = req.getParameter("userName");
                String s = userService.checkUserName(userName);
                resp.getWriter().println(s);
//                刷新
                resp.flushBuffer();
            }
        } else {
            queryUser(req, resp);
        }
        }

    private void deleteUserById(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String id = req.getParameter("id");
//               获取id
        Integer count = userService.deleteById(Integer.parseInt(id));
//                重定向查询所有用户的信息
        resp.sendRedirect("/userServlet");
    }

    //        添加用户的方法
    private void saveUpUser(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        User user = new User();
        String id = req.getParameter("id");
//        System.out.println(id);
        user.setUsername(req.getParameter("userName"));
        user.setPassword(req.getParameter("password"));
        user.setPhoneNum(req.getParameter("phoneNum"));
        user.setEmail(req.getParameter("email"));
        Integer count = -1;
        if (id == null || id.equals("")){
//                count:影响的行数
            count = userService.addUser(user);
        } else {
//            System.out.println("更新");
            user.setId(Integer.parseInt(id));
//            更新
            count = userService.updateUser(user);
        }
        if (count > 0){
//                    表示增/更成功,再做一次查询操作
            resp.sendRedirect("/userServlet");
        } else {
//                    插入失败
            System.out.println("插入失败...");
//                    跳转失败页面
        }
    }

//         查询用户信息
    private void queryUser(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        List<User> list = userService.getUser(null);
//        把查询的信息绑定在 request 作用域中
        req.setAttribute("list", list);
//        页面跳转到 user.jsp 中
        req.getRequestDispatcher("/user/user.jsp").forward(req, resp);
    }
}
